<?php

namespace App\Services;

use App\Models\Crm_Gift;
use App\Models\Crm_Gift_Record;
use App\Traits\External;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class GiftService
{
    public function getGiftRecord($params)
    {
        $result = Crm_Gift_Record::getFilter($params)
            ->select(['id', 'giftid', 'mid',  'otherid', 'fee', 'nums', 'created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $result->data = $result->makeHidden(['hasOneGift']);
        $list['total'] = $result->total();
        $item = External::optionResult($result,3);
        $list['list'] = $item;
        return $list;
    }

    public function getGiftList($params)
    {
        $result = Crm_Gift::getFilter($params)
            ->select(['id', 'giftname', 'url', 'fee', 'income','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }

    public function giftUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            if(!empty($params['id'])){
                $res = Crm_Gift::where('id',$params['id'])->update([
                    'giftname' => $params['giftname'],
                    'url' => $params['url'],
                    'fee' => $params['fee'],
                    'income' => $params['income']
                ]);
                if(!$res){
                    throw new \Exception("更新Crm_Gift礼物失败" );
                }
            }else{
                $res = Crm_Gift::create([
                    'agencyid' => $params['aid'],
                    'giftname' => $params['giftname'],
                    'url' => $params['url'],
                    'fee' => $params['fee'],
                    'income' => $params['income']
                ]);
                if(!$res){
                    throw new \Exception("新增Crm_Gift礼物失败" );
                }
            }

            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function giftDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Gift::find($params['id']);
            $res->is_del = 'Y';

            if(!$res->save()){
                throw new \Exception("删除Crm_Gift礼物失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
}
